import { Login, Logout } from "@/api/account";
import { setToken, setUsername, getUsername, getToken, removeUsername, removeToken  } from "@/utils/cookie";
const state = {
    count: 100,
    text: "学习后台管理的开发",
    collapse: JSON.parse(sessionStorage.getItem("collapse")) || false,
    token: "" || getToken(),
    username: "" || getUsername(),
};
const mutations = {
    SET_COUNT(state) {
        state.count = 10;
    },
    SET_TEXT(state, payload) {
        state.text = payload;
    },
    SET_COLLAPSE(state) {
        state.collapse = !state.collapse;
        sessionStorage.setItem("collapse", JSON.stringify(state.collapse));
    },
    SET_TOKEN(state, value) {
        state.token = value; // 设置token
        value && setToken(value); // 存在value时写入token

    },
    SET_USERNAME(state, value) { // 设置用户名
        state.username = value;
        value && setUsername(value); // 存在value时写入缓存
    }
};
const actions = {
    update_count(context, payload) {
        console.log(context, "打印context的值");
        context.conmmit("SET_COUNT");
    },
    update_text({state, mutations, actions, getters, commit }, payload) {
        commit("SET_TEXT", payload)
    },
    // context   
    loginAction({ state, commit }, payload) {
        // 返回一个promise对象,是根据login的状态进行的,login返回正常的时候,通过resolve
        // 进行返回,然后通过.then进行接收,然后login返回状态异常的时候,通过reject进行返回,
        // 使用.catch进行接收,需要看下响应拦截器的内容
        return new Promise((resolve, reject) => {
            Login(payload).then((response) => {
                let data = response.data;
                commit("SET_TOKEN", data.token);
                commit("SET_USERNAME", data.username);
                resolve(response);
            })
            .catch((error) => {
                reject(error);
            })
        })
    },
    // 登出
    logoutAction({ commit }){
        return new Promise((resolve, reject) => {
            Logout().then(response => {
                removeToken();
                removeUsername();
                commit('SET_TOKEN', '');
                commit('SET_USERNAME', '');
                resolve(response);
            })
            
        })
    }
};
const getters = {
    getCount: (state) => {
        return state.count + 10;
    },
    getText: (state) => {
        return "我正在努力" + state.text 
    }
    
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}